'''

setStyle()
QstyleFactory()  当前平台支持的样式
QApplication.setStyle()  设置样式

'''
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class AppWidget(QWidget):
    def __init__(self,parent=None):
        super(AppWidget,self).__init__(parent)
        self.setWindowTitle("双缓存绘制矩形")
        #pixmap
        self.pix=QPixmap()

        self.lastPoint=QPoint()
        self.endPoint=QPoint()
        #辅助画图
        self.tempix=QPixmap()
        #是否在作图的标志
        self.isDrawing=False
        self.initUI()
    def initUI(self):
        self.resize(600,600)
        #画布大小
        self.pix=QPixmap(450,450)
        self.pix.fill(Qt.white)
    def paintEvent(self,event):
        painter=QPainter(self)
        x=self.lastPoint.x()
        y=self.lastPoint.y()
        w=self.endPoint.x()-x
        h=self.endPoint.y()-y
        #如果正在绘图就在辅助画布上绘制
        if self.isDrawing:
            #之前的pix的内容复制到辅助画布
            self.tempix=self.pix
            pp = QPainter(self.tempix)
            #绘制矩形
            pp.drawRect(x,y,w,h)
            #重新绘制画布到窗口
            painter.drawPixmap(0,0,self.tempix)
        else:
            pp=QPainter(self.pix)
            pp.drawRect(x,y,w,h)
            painter.drawPixmap(0,0,self.pix)

    def mousePressEvent(self,event):
        #鼠标左键
        if event.button()==Qt.LeftButton:
            self.lastPoint=event.pos()
            self.endPoint=self.lastPoint
            self.isDrawing=True

    def mouseReleaseEvent(self, event):
        if event.button()== Qt.LeftButton:
            self.endPoint=event.pos()
            self.update()
            self.isDrawing=False

if __name__ == '__main__':
    app=QApplication(sys.argv)
    win=AppWidget()
    win.show()
    sys.exit(app.exec_())